import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import MyChannel from 'components/MyChannel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { PlusOutlined } from '@ant-design/icons'
import { baseURL } from 'utils/request'
import { addArticles, getArticleById, editArticleById } from 'api/articles'

export default class ArticlePublish extends Component {
  state = {
    type: 1,
    previewVisible: false,
    previewImage: '',
    fileList: [],
    isEdit: !!this.props.match.params.id,
    id: this.props.match.params.id,
  }
  formRef = React.createRef()
  async componentDidMount() {
    const { isEdit, id } = this.state
    if (isEdit) {
      const {
        data: { channel_id, content, title, cover },
      } = await getArticleById(id)
      // 修改state里面的 fileList 和 type
      this.setState({
        type: cover.type,
        fileList: cover.images.map((item) => ({ url: item })),
      })
      this.formRef.current.setFieldsValue({
        type: cover.type,
        channel_id,
        content,
        title,
      })
    }
  }
  render() {
    const { type, fileList, previewVisible, previewImage, isEdit } = this.state
    return (
      <div className={styles.publish}>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {isEdit ? '文章编辑' : '文章发布'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            labelCol={{ span: 4 }}
            initialValues={{ title: '', content: '', type: 1 }}
            onFinish={this.onFinish}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '文章标题不能为空' }]}
            >
              <Input type="text" placeholder="请输入文章标题"></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '频道不能为空' }]}
            >
              <MyChannel />
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.handleTypeChange} name="image">
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  action={`${baseURL}upload`}
                  name="image"
                  method="post"
                  onChange={this.handleFileChange}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length < type && <PlusOutlined />}
                </Upload>
              </Form.Item>
            )}
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '文章内容不能为空' }]}
            >
              <ReactQuill theme="snow" placeholder="请输入内容" />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={this.addArticles}
                  size="large"
                >
                  {isEdit ? '修改文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={this.addDarft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        <Modal
          visible={previewVisible}
          title="图片预览"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }
  handleTypeChange = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  handleFileChange = ({ file, fileList }) => {
    this.setState({
      fileList,
    })
  }
  handlePreview = (file) => {
    console.log(file)
    this.setState({
      previewVisible: true,
      previewImage: file.url || file.response.data.url,
    })
  }
  handleCancel = () => {
    this.setState({
      previewVisible: false,
      previewImage: '',
    })
  }
  beforeUpload = (file) => {
    if (file.size / 1024 > 500) {
      message.error('上传的图片过大，超过500KB！！')
      return Upload.LIST_IGNORE
    }
    if (!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
      message.error('上传图片仅支持jpeg、jpg、png格式！！')
      return Upload.LIST_IGNORE
    }
    return true
  }
  save = async (values, draft = false) => {
    const { isEdit, id } = this.state
    const images = this.state.fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const data = {
      ...values,
      cover: {
        type: values.type,
        images,
      },
    }
    if (isEdit) {
      // 修改文章--发送请求
      await editArticleById(id, data, draft)
      message.success('修改文章成功')
    } else {
      // 发布文章--发送请求
      await addArticles(data, draft)
      message.success('添加文章成功')
    }

    this.props.history.push('/home/list')
  }
  // 点击-发表文章
  onFinish = (values) => {
    this.save(values, false)
  }
  // 点击-保存草稿
  addDarft = async () => {
    // console.log(this.formRef.current)
    try {
      const values = await this.formRef.current.validateFields()
      this.save(values, true)
    } catch (e) {
      console.log(e)
    }
  }
}
